// WebSocket.js
import { useUserStore } from "@/stores/user.js";

class WebSocketService {
    constructor(url) {
        this.socket = null;
        this.url = url;
        this.callbacks = {};
        this.connectionPromise = null;
        this.resolveConnection = null;
        this.isConnected = false; // 新增标志位
    }

    // 连接WebSocket
    connect() {
        return new Promise((resolve, reject) => {
            this.socket = new WebSocket(this.url);

            this.socket.onopen = () => {
                console.log('WebSocket连接已建立');

                    this.callbacks['open']();

                resolve();

                    // this.resolveConnection();
                    // this.resolveConnection = null;

                this.isConnected = true; // 设置标志位为已连接
                this.send({ type: 'setId', userId: useUserStore().userId });
            };

            this.socket.onmessage = (event) => {
                const data = JSON.parse(event.data);
                // 处理接收到的消息
                console.log('收到消息:', data);

                    this.callbacks['message'](data);

            };

            this.socket.onclose = () => {
                console.log('WebSocket连接已关闭');
                this.isConnected = false; // 设置标志位为未连接

                    this.callbacks['close']();


                    this.rejectConnection(new Error('WebSocket connection closed'));
                    this.rejectConnection = null;

            };

            this.socket.onerror = (error) => {
                console.error('WebSocket发生错误:', error);

                    this.callbacks['error'](error);


                    this.rejectConnection(error);
                    this.rejectConnection = null;

            };
        });
    }

    // 发送消息
    async send(message) {
        try {
            await this.ensureConnection();
            if (this.socket && this.socket.readyState === WebSocket.OPEN && this.isConnected) {
                console.log('发送消息:', message);
                this.socket.send(JSON.stringify(message));
            } else {
                console.error('WebSocket未连接，无法发送消息');
            }
        } catch (error) {
            console.error('Failed to ensure WebSocket connection before sending message:', error);
        }
    }

    // 确保连接
    ensureConnection() {
        if (this.connectionPromise) {
            return this.connectionPromise;
        }
        if (this.socket && this.socket.readyState === WebSocket.OPEN && this.isConnected) {
            return Promise.resolve();
        }
        this.connectionPromise = new Promise((resolve, reject) => {
            this.resolveConnection = resolve;
            this.rejectConnection = reject;
            this.connect().then(resolve).catch(reject);
        }).finally(() => {
            this.connectionPromise = null;
        });
        return this.connectionPromise;
    }

    // 注册回调函数
    on(event, callback) {
        this.callbacks[event] = callback;
    }

    // 关闭WebSocket连接
    close() {
        if (this.socket) {
            this.socket.close();
        }
    }
}

export default WebSocketService;